<template>
  <div class="import-manager">
    <el-card class="import-card">
      <div slot="header">
        <span>导入书签</span>
      </div>
      
      <el-alert
        title="支持从浏览器导出的书签 HTML 文件导入"
        type="info"
        description="请先在浏览器中导出书签为 HTML 文件，然后在此处上传导入。"
        :closable="false"
        show-icon
      ></el-alert>
      
      <div class="upload-area" style="margin-top: 20px;">
        <el-upload
          class="upload-html"
          drag
          action="#"
          :http-request="handleUpload"
          :before-upload="beforeUpload"
          accept=".html,.htm"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将书签文件拖到此处，或<em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            只能上传 HTML 文件
          </div>
        </el-upload>
      </div>
      
      <!-- 导入预览 -->
      <div v-if="previewData.length" class="preview-area" style="margin-top: 20px;">
        <div class="preview-header">
          <div class="preview-info">
            <h3>导入预览</h3>
            <p>共找到 {{ previewData.length }} 个书签，已选择 {{ selectedBookmarks.length }} 个</p>
          </div>
          <div class="preview-actions">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleSelectAll(true)"
              :disabled="previewData.length === selectedBookmarks.length"
            >
              全选
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="handleSelectAll(false)"
              :disabled="selectedBookmarks.length === 0"
            >
              取消全选
            </el-button>
          </div>
        </div>
        
        <el-table
          ref="previewTable"
          :data="previewData"
          style="width: 100%; margin-top: 15px;"
          height="400"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          
          <el-table-column
            prop="title"
            label="标题"
            min-width="200"
          >
            <template slot-scope="scope">
              <div class="bookmark-title-cell">
                <div class="icon-wrapper" @click="handleIconClick(scope.row)">
                  <img v-if="scope.row.icon" :src="scope.row.icon" class="bookmark-icon" />
                  <i v-else class="el-icon-picture-outline"></i>
                </div>
                <el-link
                  :href="scope.row.url"
                  target="_blank"
                  type="primary"
                >
                  {{ scope.row.title }}
                </el-link>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column
            prop="url"
            label="URL"
            min-width="300"
            show-overflow-tooltip
          ></el-table-column>
          
          <el-table-column
            prop="category"
            label="分类"
            width="200"
          >
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.category"
                placeholder="请选择分类"
                size="small"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in categories"
                  :key="item._id"
                  :label="item.name"
                  :value="item._id"
                >
                  <span style="float: left">
                    <i :class="item.icon || 'el-icon-folder'" :style="{ color: item.color }"></i>
                    {{ item.name }}
                  </span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="import-actions" style="margin-top: 20px; text-align: right;">
          <el-button @click="previewData = []">取消</el-button>
          <el-button
            type="primary"
            :loading="importing"
            :disabled="!canImport"
            @click="handleImport"
          >
            {{ importing ? '导入中...' : `导入选中的 ${selectedBookmarks.length} 个书签` }}
          </el-button>
        </div>
      </div>
      
      <!-- 导入进度 -->
      <el-dialog
        title="导入进度"
        :visible.sync="progressVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
        width="400px"
      >
        <div class="progress-info">
          <p>正在导入第 {{ importedCount }} 个，共 {{ totalCount }} 个</p>
          <el-progress
            :percentage="importProgress"
            :format="progressFormat"
          ></el-progress>
        </div>
      </el-dialog>
      
      <!-- 隐藏的文件输入用于处理粘贴的图片 -->
      <input
        type="file"
        ref="iconInput"
        accept="image/*"
        style="display: none"
        @change="handleIconFileChange"
      >
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { createBookmarksBatch } from '@/api/bookmark'

export default {
  name: 'ImportManager',
  data() {
    return {
      previewData: [],
      selectedBookmarks: [],
      importing: false,
      progressVisible: false,
      importedCount: 0,
      totalCount: 0,
      currentEditingBookmark: null
    }
  },
  computed: {
    ...mapState(['categories']),
    canImport() {
      return this.selectedBookmarks.length > 0 &&
        this.selectedBookmarks.every(item => item.category)
    },
    importProgress() {
      if (!this.totalCount) return 0
      return Math.round((this.importedCount / this.totalCount) * 100)
    }
  },
  created() {
    // 获取分类列表
    this.$store.dispatch('fetchCategories')
  },
  mounted() {
    // 添加粘贴事件监听
    document.addEventListener('paste', this.handlePaste);
  },
  beforeDestroy() {
    // 移除粘贴事件监听
    document.removeEventListener('paste', this.handlePaste);
  },
  methods: {
    beforeUpload(file) {
      const isHTML = file.type === 'text/html' ||
        file.name.endsWith('.html') ||
        file.name.endsWith('.htm')
      
      if (!isHTML) {
        this.$message.error('只能上传 HTML 文件！')
        return false
      }
      
      return true
    },
    handleUpload({ file }) {
      const reader = new FileReader()
      
      reader.onload = e => {
        const content = e.target.result
        const parser = new DOMParser()
        const doc = parser.parseFromString(content, 'text/html')
        const bookmarks = []
        
        // 解析所有书签链接
        doc.querySelectorAll('a[href]').forEach(link => {
          bookmarks.push({
            title: link.textContent.trim(),
            url: link.href,
            category: '',
            description: link.getAttribute('description') || ''
          })
        })
        
        if (bookmarks.length === 0) {
          this.$message.warning('未在文件中找到任何书签')
          return
        }
        
        this.previewData = bookmarks
        this.$message.success('成功解析 ' + bookmarks.length + ' 个书签')
      }
      
      reader.onerror = () => {
        this.$message.error('文件读取失败')
      }
      
      reader.readAsText(file)
    },
    progressFormat() {
      return this.importedCount + '/' + this.totalCount
    },
    handleSelectionChange(val) {
      this.selectedBookmarks = val;
    },
    
    handleSelectAll(select) {
      this.$refs.previewTable.toggleAllSelection();
    },
    
    handleIconClick(bookmark) {
      this.currentEditingBookmark = bookmark;
      this.$refs.iconInput.click();
    },
    
    handleIconFileChange(event) {
      const file = event.target.files[0];
      if (file && this.currentEditingBookmark) {
        this.processImageFile(file, this.currentEditingBookmark);
      }
      // 清除文件选择，以便能够选择相同的文件
      event.target.value = '';
    },
    
    handlePaste(event) {
      const items = (event.clipboardData || event.originalEvent.clipboardData).items;
      
      for (const item of items) {
        if (item.type.indexOf('image') === 0) {
          const file = item.getAsFile();
          if (this.currentEditingBookmark) {
            this.processImageFile(file, this.currentEditingBookmark);
          }
          break;
        }
      }
    },
    
    processImageFile(file, bookmark) {
      const reader = new FileReader();
      reader.onload = (e) => {
        bookmark.icon = e.target.result;
      };
      reader.readAsDataURL(file);
    },
    
    async handleImport() {
      if (this.selectedBookmarks.length === 0) {
        this.$message.warning('请至少选择一个书签');
        return;
      }
      
      this.importing = true;
      this.progressVisible = true;
      this.importedCount = 0;
      this.totalCount = this.selectedBookmarks.length;
      
      try {
        // 只处理选中的书签，并且移除_id字段
        const bookmarks = this.selectedBookmarks.map(item => {
          if (!item.category) {
            throw new Error('选中的书签中有未设置分类的项目');
          }
          
          // 创建一个新对象，只包含需要的字段
          return {
            title: item.title,
            url: item.url,
            category: item.category,
            description: item.description || '',
            icon: item.icon || ''
          };
        });

        // 批量创建书签
        await createBookmarksBatch({ bookmarks });
        
        // 刷新书签列表
        await this.$store.dispatch('fetchBookmarks');
        
        this.$message.success(`成功导入 ${this.selectedBookmarks.length} 个书签`);
        this.previewData = [];
      } catch (error) {
        this.$message.error(error.message || '导入失败');
      } finally {
        this.importing = false;
        this.progressVisible = false;
      }
    }
  }
}
</script>

<style lang="less" scoped>
.import-manager {
  .import-card {
    margin: 0 auto;
    max-width: 1000px;
  }
  
  .upload-area {
    .upload-html {
      width: 100%;
    }
  }
  
  .preview-area {
    .preview-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .preview-info {
        h3 {
          margin: 0;
          font-size: 16px;
          color: #303133;
        }
        
        p {
          margin: 10px 0 0;
          color: #606266;
        }
      }
      
      .preview-actions {
        .el-button {
          margin-left: 10px;
        }
      }
    }
  }
  
  .progress-info {
    text-align: center;
    
    p {
      margin: 0 0 15px;
      color: #606266;
    }
  }
  
  .bookmark-title-cell {
    display: flex;
    align-items: center;
    
    .icon-wrapper {
      width: 24px;
      height: 24px;
      margin-right: 10px;
      border: 1px dashed #dcdfe6;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      
      &:hover {
        border-color: #409EFF;
        color: #409EFF;
      }
      
      .bookmark-icon {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
      
      i {
        font-size: 16px;
        color: #909399;
      }
    }
  }
}
</style> 